package com.zhb.util;

import com.google.common.collect.Lists;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Set;

import static org.apache.http.Consts.UTF_8;

/**
 * Created by jarvan4dev on 16/5/21.
 */
public class HttpUtils {

    public static String doPost(HttpClient httpClient, String requestUri, Map<String, Object> params) throws IOException {
        String result = null;
        HttpPost post = new HttpPost(requestUri);
        try {
            Set<Map.Entry<String, Object>> entrySet = params.entrySet();
            List<NameValuePair> nameValuePairs = Lists.newArrayList();
            for (Map.Entry<String, Object> entry : entrySet){
                nameValuePairs.add(new BasicNameValuePair(entry.getKey(), String.valueOf(entry.getValue())));
            }
            //url格式编码
            UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(nameValuePairs, UTF_8);
            post.setEntity(uefEntity);
            HttpResponse httpResponse = httpClient.execute(post);
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            if (statusCode == HttpStatus.SC_OK){
                result = EntityUtils.toString(httpResponse.getEntity());
            } else if (statusCode == HttpStatus.SC_MOVED_TEMPORARILY){
                System.out.println("重定向到: " +  httpResponse.getFirstHeader("Location"));
            }
        }finally {
            post.releaseConnection();
        }
        return result;
    }

    public static String doGet(HttpClient httpClient, String requestUri) throws IOException {
        String result = null;
        HttpGet get = new HttpGet(requestUri);

        /**
         * setConnectTimeout：设置连接超时时间，单位毫秒。
         * setConnectionRequestTimeout：设置从connect Manager获取Connection 超时时间，单位毫秒。这个属性是新加的属性，因为目前版本是可以共享连接池的。
         * setSocketTimeout：请求获取数据的超时时间，单位毫秒。 如果访问一个接口，多少时间内无法返回数据，就直接放弃此次调用。
         */
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(50000).setConnectionRequestTimeout(10000)
                .setSocketTimeout(50000).build();

        get.setConfig(requestConfig);
        setHeader(get);
        try {
            HttpResponse httpResponse = httpClient.execute(get);
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            if (statusCode == HttpStatus.SC_OK){
                result = EntityUtils.toString(httpResponse.getEntity());
            }
        } finally {
            Header[] headers = get.getAllHeaders();
            for (Header header : headers){
                System.out.println(header.getName() + ":" + header.getValue());
            }
            get.releaseConnection();
        }
        return result;
    }

    private static void setHeader(HttpGet get){
        get.setHeader("Accept-Encoding", "gzip, deflate");
        get.setHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:46.0) Gecko/20100101 Firefox/46.0");
        get.setHeader("Host", "api.interlib.com.cn:6699");
        get.setHeader("Accept", "*/*");
        get.setHeader("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3");
        get.setHeader("Connection", "keep-alive");
    }
}
